package com.cutter.mobile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class mergefiles extends Activity {
	protected static final int REQUEST_CODE_PICK_FILE_OR_DIRECTORY = 1;
	private ProgressDialog pd;
	private String DestPath;
	private String DestFile;
	private String OrigFile;
	private String MD5;
	private String Activefilename = "";
	private String msg = "";
	private boolean SplitDone = false;
	MenuInflater inflater;
	Button SelFolderbut;
	Button StartBut;
	Button GetMd5But;
	Button RunFileBut; 
	TextView mergemessage;
	MenuItem mnuMD5;
	MenuItem mnuShowReadMe;
	MenuItem mnuOpenFile;
	MenuItem mnuRepeat;
	
	@Override    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mergelayout); 
        Intent myIntent = getIntent();
        
        SelFolderbut = (Button) findViewById(R.id.SelZSP);
        SelFolderbut.setText(getText(R.string.mergefilebut1));
        StartBut = (Button) findViewById(R.id.StartMerge);
        StartBut.setText(getText(R.string.prooceedbut));
        mergemessage = (TextView) findViewById(R.id.TextView01);
        
        if (myIntent.getData() != null) {
        
        	String zspFile = "";
        	try {
        		zspFile = new URI(myIntent.getDataString()).getPath();
        		File myZSP = new File(zspFile);
        		Activefilename = myZSP.getName();
        		DestPath = myZSP.getParent();
        		OrigFile = Activefilename;
    			OrigFile = OrigFile.substring(0, OrigFile.lastIndexOf('.'));
    			String tt = (String) getText(R.string.readytomerge);
        		msg=String.format(tt, OrigFile,DestPath);
        		ShowMSG(msg);
        		SelFolderbut.setVisibility(View.GONE);    
        		StartBut.setEnabled(true);        		
        	} catch (URISyntaxException e) {
        		// TODO Auto-generated catch block
        		e.printStackTrace();
        	}
        } else {             
        	StartBut.setEnabled(false);        	
        }
        StartBut.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String ffName = OrigFile; //="/sdcard/download/Cutter_Output_(help.pdf)/help.pdf.zsp";
				String Destfold = DestPath; //="/sdcard/download/Cutter_Output_(help.pdf)/";
				String pdtitle = (String) getText(R.string.rebuildtitle);
				pdtitle = String.format(pdtitle, OrigFile);
				
				pd = new ProgressDialog(mergefiles.this);
    			pd.setTitle(pdtitle);
    			pd.setIndeterminate(true);
    			pd.setCancelable(true);
    			pd.show();
				
    			MergeFileTask doMerge = new MergeFileTask();
				doMerge.execute(Activefilename, DestPath, OrigFile);
				
			}
		});
        
        SelFolderbut.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
            	Intent intent = new Intent("org.openintents.action.PICK_FILE"); 
            	intent.putExtra("org.openintents.extra.TITLE", getString(R.string.selfiledialogtitle));
        		intent.putExtra("org.openintents.extra.BUTTON_TEXT", getString(R.string.selfiledialogbut));        		
        		startActivityForResult(intent, REQUEST_CODE_PICK_FILE_OR_DIRECTORY);
            }
        });       
        
	}
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
			switch (requestCode) {
			case REQUEST_CODE_PICK_FILE_OR_DIRECTORY:
				if (resultCode == RESULT_OK && data != null && getExtension(data.getDataString()).compareToIgnoreCase("zsp")==0) {
					try {
						String SelFile = new URI(data.getDataString()).getPath().toString();
						Activefilename = SelFile;
						File myZSP = new File(SelFile);
		        		DestPath = myZSP.getParent();
		        		OrigFile = myZSP.getName();
		    			OrigFile = OrigFile.substring(0, OrigFile.lastIndexOf('.'));
		    			String tt = (String) getText(R.string.readytomerge);
		        		msg = String.format(tt, OrigFile,DestPath);
		        		mergemessage.setText(Html.fromHtml(msg));
		        		StartBut.setEnabled(true);		        		
					} catch (URISyntaxException e1) {						
						e1.printStackTrace();
					} 
						
				} else {
					NoZspMessageBox();
					StartBut.setEnabled(false);						
				}
				
				break;
			} 	
		}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
        inflater = getMenuInflater();        
        inflater.inflate(R.menu.mergemenu, menu);
        mnuMD5 = menu.findItem(R.id.getmd5menu);
        mnuMD5.setTitle(getText(R.string.getmd5));
		mnuMD5.setEnabled(false);
		mnuShowReadMe = menu.findItem(R.id.showreadme);
		mnuShowReadMe.setTitle(getText(R.string.showreadme));
		mnuShowReadMe.setEnabled(false);
		mnuRepeat = menu.findItem(R.id.repeatmerge);
		mnuRepeat.setTitle(getText(R.string.repeatmerge));
		mnuRepeat.setEnabled(false);
		mnuOpenFile = menu.findItem(R.id.openfile);
		mnuOpenFile.setTitle(getText(R.string.runfile));
		mnuOpenFile.setEnabled(false);
		return true;
    }
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		mnuMD5.setEnabled(SplitDone);
		mnuRepeat.setEnabled(SplitDone);
		mnuOpenFile.setEnabled(SplitDone);		
		File readmefile = new File(DestPath+"/Readme.txt");
		mnuShowReadMe.setEnabled((readmefile.exists()));
		return true;
    }
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.openfile:
            File aFile = new File(DestPath+"/"+OrigFile);
            //Toast.makeText(this, aFile.getPath(), Toast.LENGTH_LONG).show();
            openFile(aFile);
            return true;
        case R.id.repeatmerge:
        	String pdtitle = (String) getText(R.string.rebuildtitle);
			pdtitle = String.format(pdtitle, OrigFile);
			
			pd = new ProgressDialog(mergefiles.this);
			pd.setTitle(pdtitle);
			pd.setIndeterminate(true);
			pd.setCancelable(true);
			pd.show();
			
			MergeFileTask doMerge = new MergeFileTask();
			doMerge.execute(Activefilename, DestPath, OrigFile);
            
            return true;
        case R.id.showreadme:
            ShowReadMe(DestPath+"/Readme.txt");
            return true;
        case R.id.getmd5menu:
            String dFile=DestPath+"/"+OrigFile;
            String md5sum="";
            try {
				md5sum = getMd5FileHash(new File(dFile));
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				Toast.makeText(mergefiles.this, md5sum, Toast.LENGTH_LONG).show();
			}
            
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
	private void ShowMSG(String mess) {
		mergemessage.setText(Html.fromHtml(mess));
	}
	private class MergeFileTask extends AsyncTask<String, String, String> {
		private String OFile; 
		
		@Override
		protected String doInBackground(String... params) {
			
			File inFile;
			File outFile;
			String inFN;
			inFN = params[0];
			String outFN = inFN;
			outFN = DestPath+"/"+params[2];
			OFile = DestPath+"/"+params[2];
			FileInputStream fileIS = null;
			outFile = new File(outFN);
			if (outFile.exists()) {
				outFile.delete();
			}
			FileOutputStream fileOS;
			try {
				fileOS = new FileOutputStream(outFile);
				int c=0;
				boolean GoOn=true;
				while (GoOn){
					inFile= new File(inFN);					
					fileIS = new FileInputStream(inFN); 
					byte[] data = new byte[(int) inFile.length()];  
					int count = fileIS.read(data); 
					fileIS.close();
					fileOS.write(data,0,count); 
					fileOS.flush();
					publishProgress(inFN, Long.toString(inFile.length()), params[2]);	
					//Thread.sleep(2000);
					c++;
					inFN = outFN+"."+c;
					File NextFile = new File(inFN);
					if (NextFile.exists()==false) {
						GoOn=false;
						break;
					}
								
				}
				fileOS.close();
			} catch (Exception e) {
				
			};
			
			return null;
   	}
		@Override		
		protected void onProgressUpdate(String... values) {
			pd.setMessage(values[0]);
	      }

	      @Override
	      protected void onPostExecute(String result) {
	       
	         pd.dismiss();
	         SuccessMessageBox();
	         SplitDone=true;
	         
	      }

		
    }
	
	public int SuccessMessageBox() {
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(getText(R.string.mergesuccess));
		alt_bld.setCancelable(false);
		alt_bld.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
								
		}
		});
		
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(getText(R.string.successtitle));
		// Icon for AlertDialog
		alert.setIcon(R.drawable.info48);
		//alert.setIcon(R.drawable.icon);
		alert.show();				
		return 0;		
	}
	public int NoZspMessageBox() {
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(getText(R.string.nozspselected));
		alt_bld.setCancelable(false);
		alt_bld.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
								
		}
		});
		
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(getText(R.string.errortitle));
		// Icon for AlertDialog
		alert.setIcon(R.drawable.info48);
		//alert.setIcon(R.drawable.icon);
		alert.show();				
		return 0;		
	}
	public static String getMd5FileHash(File input) throws NoSuchAlgorithmException, IOException {
        MessageDigest md = MessageDigest.getInstance("MD5");
    	InputStream is = new FileInputStream(input);
    	byte[] buffer = new byte[8192];
    	int read = 0;       	
    	while( (read = is.read(buffer)) > 0) {
    		md.update(buffer, 0, read);
    	}		
    		byte[] md5sum = md.digest();
    		BigInteger bigInt = new BigInteger(1, md5sum);
    		String output = bigInt.toString(16);
		return output;
	
}	
	public static String getExtension(String f) {
        File myFile = new File(f);
		String ext = null;
        String s = myFile.getName();
        int i = s.lastIndexOf('.');
 
        if (myFile.isDirectory())
        	ext = null;
        else if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
    }
	public int ShowReadMe(String ReadmeFile) {
		
		File file = new File(ReadmeFile);
        StringBuffer contents = new StringBuffer();
        BufferedReader reader = null;

        try
        {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            // repeat until all lines is read
            while ((text = reader.readLine()) != null)
            {
                contents.append(text)
                    .append(System.getProperty(
                        "line.separator"));
            }
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (reader != null)
                {
                    reader.close();
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        
		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage(contents.toString());
		alt_bld.setCancelable(false);
		alt_bld.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
								
		}
		});
		AlertDialog alert = alt_bld.create();
		// Title for AlertDialog
		alert.setTitle(getText(R.string.readmetitle));
		// Icon for AlertDialog
		alert.setIcon(R.drawable.info48);
		//alert.setIcon(R.drawable.icon);
		alert.show();				
		return 0;		
	}
	 @SuppressWarnings("null")
	private void openFile(File aFile) { 
		 
		 String myFile = aFile.getPath();
		 String myext = getExtension(myFile);
		 String mimeType= MimeTypeMap.getSingleton().getMimeTypeFromExtension(myext);
		 Uri data = Uri.fromFile(aFile);
		 Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
		 
		 intent.setDataAndType(data, mimeType);
		 
		 try {
             startActivity(intent); 
		 } catch (ActivityNotFoundException e) {
             Toast.makeText(this, "no app", Toast.LENGTH_SHORT).show();
		 }
     } 
}
